package com.linkage.jz.bankruptcy.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingAboutActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingFeedbackActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingRePwdActivity;
import com.linkage.jz.bankruptcy.activity.Project.FavProListActivity;
import com.linkage.jz.bankruptcy.activity.Project.MyProListActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.AccountLoginActivity;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.bean.MyAddr;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.seapeak.activity.register.RegisterActivity;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.tab_more_item_view;
//import com.linkage.seapeak.activity.user.PersonalAddressActivity;
import com.linkage.seapeak.activity.user.PersonalAddressActivity;
import com.linkage.seapeak.activity.user.ThridAuthActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.mob.wrappers.ShareSDKWrapper.getToken;

/**
 * Created by caobotao on 16/1/4.
 */
public class SettingFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private ImageView avatarImageView, line_1, line_2, line_3, line_4;

    private SwipeRefreshLayout swipe_content;
    private RelativeLayout r_personsetting, userinfo;
    private LinearLayout ll_progect,ll_mypro,ll_favpro;
    private tab_more_item_view r_about, r_repwd, r_feedback, otherLogin, myaddr;
    private TextView user_name, user_phone, my_project_num, watch_project_num;

    private static Boolean DEBUG = false;
    private boolean initData = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab_setting, container, false);
        initData = true;
        avatarImageView = (ImageView) view.findViewById(R.id.iv_avatar);
        r_personsetting = (RelativeLayout) view.findViewById(R.id.r_personsetting);
        r_repwd = (tab_more_item_view) view.findViewById(R.id.r_repwd);
        r_feedback = (tab_more_item_view) view.findViewById(R.id.r_feedback);
        r_about = (tab_more_item_view) view.findViewById(R.id.r_about);
        otherLogin = (tab_more_item_view) view.findViewById(R.id.otherLogin);
        myaddr = (tab_more_item_view) view.findViewById(R.id.myaddr);
        ll_progect = (LinearLayout) view.findViewById(R.id.ll_progect);
        user_name = (TextView) view.findViewById(R.id.user_name);
        userinfo = (RelativeLayout) view.findViewById(R.id.userinfo);
        user_phone = (TextView) view.findViewById(R.id.user_phone);
        line_1 = (ImageView) view.findViewById(R.id.line_1);
        line_2 = (ImageView) view.findViewById(R.id.line_2);
        line_3 = (ImageView) view.findViewById(R.id.line_3);
        line_4 = (ImageView) view.findViewById(R.id.line_4);
        ll_mypro = (LinearLayout)view.findViewById(R.id.ll_mypro);
        ll_favpro = (LinearLayout)view.findViewById(R.id.ll_favpro);
        my_project_num = (TextView) view.findViewById(R.id.my_project_num);
        swipe_content = (SwipeRefreshLayout) view.findViewById(R.id.swipe_content);
        watch_project_num = (TextView) view.findViewById(R.id.watch_project_num);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        swipe_content.setColorSchemeColors(0xff25b6ed, 0xff6dbcdb, 0xfff0b650, 0xffff534e, 0xffbed73d, 0xff04bfbf,
                0xffff530d, 0xff61bc46);
        swipe_content.setOnRefreshListener(this);
        swipe_content.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //模拟网络请求需要3000毫秒，请求完成，设置setRefreshing 为false
                updataUserInfo();
            }
        });

        otherLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ThridAuthActivity.class);
                getActivity().startActivity(intent);
            }
        });

        myaddr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), PersonalAddressActivity.class);
                getActivity().startActivity(intent);
//                PersonSettingAddrActivity.start(getActivity());
            }

        });

        userinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String UserLogin = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
                if ("".equalsIgnoreCase(UserLogin)) {
//                    RegisterActivity.start(getActivity());
                    AccountLoginActivity.start(getActivity());
                }
//                PersonSettingActivity.start(getActivity());
            }
        });
        ll_mypro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                RefreshEvent event = new RefreshEvent();
                event.setType(RefreshEvent.TYPE_MY_PRO);
                EventBus.getDefault().post(event);
//                    MyProListActivity.start(getActivity());

//                PersonSettingActivity.start(getActivity());
            }
        });

        ll_favpro.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                            FavProListActivity.start(getActivity());

//                PersonSettingActivity.start(getActivity());
                    }
                });
        r_personsetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String UserLogin = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
                if (DEBUG) {
                    UserLogin = "1";
                }
                if ("".equalsIgnoreCase(UserLogin)) {
                    AccountLoginActivity.start(getActivity());
                } else {
                    PersonSettingActivity.start(getActivity());
                }
            }
        });


        r_repwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(BankruptcyApp.loginInfo!=null) {
                    if ("setting".equalsIgnoreCase(BankruptcyApp.loginInfo.getPassWordTag())) {
                        PersonSettingRePwdActivity.start(getActivity(), 0);
                    } else {
                        PersonSettingRePwdActivity.start(getActivity(), 1);
                    }
                }
            }
        });


        r_feedback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PersonSettingFeedbackActivity.start(getActivity());
            }
        });

        r_about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PersonSettingAboutActivity.start(getActivity());
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();  // Always call the superclass method first
//        if (initData) {
            updateView();
        updataUserInfo();
//        }
    }

    @Subscribe
    public void getEventBus(MainActivity.ShowHideClearAll clearAll) {
        updateView();
        updataUserInfo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);

    }

    public void updateView() {
        //相当于Fragment的onResume
//            int i=0;
        String UserLogin = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        if ("".equalsIgnoreCase(UserLogin)) {
//                r_about.setVisibility(View.GONE);
            r_repwd.setVisibility(View.GONE);
            r_feedback.setVisibility(View.GONE);
            otherLogin.setVisibility(View.GONE);
            myaddr.setVisibility(View.GONE);
            line_2.setVisibility(View.GONE);
            line_3.setVisibility(View.GONE);
            line_4.setVisibility(View.GONE);
            ll_progect.setVisibility(View.GONE);
            user_name.setText("注册/登录");
            user_phone.setVisibility(View.GONE);
            avatarImageView.setImageResource(R.drawable.logo);
        } else {
//            updataUserInfo();
            r_repwd.setVisibility(View.VISIBLE);
            r_feedback.setVisibility(View.VISIBLE);
            otherLogin.setVisibility(View.VISIBLE);
            myaddr.setVisibility(View.VISIBLE);
            ll_progect.setVisibility(View.VISIBLE);
            line_1.setVisibility(View.VISIBLE);
            line_2.setVisibility(View.VISIBLE);
            line_3.setVisibility(View.VISIBLE);
            line_4.setVisibility(View.VISIBLE);
            if (BankruptcyApp.loginInfo != null) {
                /**
                 * todo 现在木得数字，加个todo免得忘记
                 */
//                    my_project_num.setText(BankruptcyApp.loginInfo.get);
//                    watch_project_num.setText(BankruptcyApp.loginInfo.get);
                user_name.setText(BankruptcyApp.loginInfo.getUsername());
                if (!TextUtils.isEmpty(BankruptcyApp.loginInfo.getMobile())) {
                    user_phone.setVisibility(View.VISIBLE);
                    String mobile = BankruptcyApp.loginInfo.getMobile();
                    if (mobile.length() > 7)
                        mobile = mobile.substring(0, 3) + "****" + mobile.substring(7);
                    user_phone.setText(mobile);
                } else
                    user_phone.setVisibility(View.GONE);
                Glide.with(this).load(BankruptcyApp.loginInfo.getAvatar())
                        .bitmapTransform(new CropCircleTransformation(getActivity()))
                        .error(R.drawable.logo)
                        .placeholder(avatarImageView.getDrawable())
                        .dontAnimate()
                        .into(avatarImageView);
            }
        }
    }

    public void updataUserInfo() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {

            if (swipe_content.isRefreshing())
                swipe_content.setRefreshing(false);
            return;
        }
//        protected String getUserToken(){
            String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        if("".equalsIgnoreCase(userToken))
        {
            if (swipe_content.isRefreshing())
                swipe_content.setRefreshing(false);
            return;
        }
        Network.getAPIService()
                .getUserInfo(userToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        if (swipe_content.isRefreshing())
                            swipe_content.setRefreshing(false);
                        int code = json.get("code").getAsInt();
                        if (code == 0) {
//                            super.onNext(json);
//                            return;
//                        } else {
                            Gson gson = new Gson();
                            JsonObject data = json.getAsJsonObject("data");

                            SPUtils.getInstance(Consts.SPNAME).put("userInfo", data.toString());
                            LoginInfo info = gson.fromJson(data.get("userInfo"), LoginInfo.class);
                            String strdata = data.toString();
                            try {
                                JSONObject jsonData = new JSONObject(strdata);
                                String  jsonPass = jsonData.optString("passWordTag");
//                                String passWordTag = jsonPass.getAsString();
                                String baseUrl = jsonData.optString("baseUrl");
//                                String baseUrl = baseUrljson.getAsString();

                                info.setPassWordTag(jsonPass);
                                info.setBaseUrl(baseUrl);
                                if ("setting".equalsIgnoreCase(jsonPass)) {
                                    r_repwd.textView.setText("设置密码");
                                } else {
                                    r_repwd.textView.setText("修改密码");
                                }
                                my_project_num.setText(jsonData.optString("myProjectNum"));

                                watch_project_num.setText(jsonData.optString("projectFocusNum"));
                                SPUtils.getInstance(Consts.SPNAME).put("userId", info.getId());
                                BankruptcyApp.loginInfo = info;
                                updateView();
                            }catch (Exception ex)
                            {
                                ex.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        if (swipe_content.isRefreshing())
                            swipe_content.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (swipe_content.isRefreshing())
                            swipe_content.setRefreshing(false);
                        super.onError(e);
                    }
                });
    }

    @Override
    public void onRefresh() {
        updateView();
    }
}
